import { ref } from "vue";

import {
  requestGetCategory1,
  requestGetCategory2,
  requestGetCategory3,
} from "@/api/category";

import type { ResCategory1, ResCategory2, ResCategory3 } from "@/api/category";

// 一级分类的数据
const categories1 = ref<ResCategory1[]>([]);
const categories2 = ref<ResCategory2[]>([]);
const categories3 = ref<ResCategory3[]>([]);

// 当前选择的一级分类id
const category1Id = ref("");
const category2Id = ref("");
const category3Id = ref("");

async function getCategories1() {
  try {
    categories1.value = await requestGetCategory1();
  } catch (e) {}
}
async function getCategories2() {
  try {
    category2Id.value = category3Id.value = "";
    categories2.value = [];
    categories3.value = [];
    categories2.value = await requestGetCategory2(Number(category1Id.value));
  } catch (e) {}
}
async function getCategories3() {
  try {
    category3Id.value = "";
    categories3.value = [];
    categories3.value = await requestGetCategory3(Number(category2Id.value));
  } catch (e) {}
}

export default function useCategorySelector() {
  return {
    category1Id,
    category2Id,
    category3Id,

    categories1,
    categories2,
    categories3,

    getCategories1,
    getCategories2,
    getCategories3,
  };
}
